package main

import (
	"Github-Repo-Issues/models"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
)

const issueurl = "https://api.github.com/repos/HarshCasper/Rotten-Scripts/issues"

func main() {

	res, err := http.Get(issueurl)
	if err != nil {
		log.Fatal(err)
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err.Error())
	}
	issues := []models.IssueDetails{}
	json.Unmarshal(body, &issues)

	showIssue(issues)
}

func showIssue(issues []models.IssueDetails) {

	var option int
	showAllIssues(issues)
	fmt.Printf("\n\nSelect the Issues you want to see: >> ")
	fmt.Scanf("%d", &option)
	option--
	showDetailIssue(issues, option)

}
func showAllIssues(issues []models.IssueDetails) {
	k := 0
	fmt.Printf("\n\n\t\t\tHere are all the Issues:\n\n")
	for i := range issues {
		k++
		fmt.Printf("\t%v. %v\n", k, issues[i].Title)
	}

}

func showDetailIssue(issues []models.IssueDetails, i int) {
	fmt.Printf("\n\t\tIssue No: #%v\n\n\t%v\n", issues[i].Number, issues[i].Title)
	fmt.Printf("\n Issue Generated By: %v %v (%v)\n\n", issues[i].AuthorAssociation, issues[i].IssueUser.Login, issues[i].IssueUser.HTMLURL)
	fmt.Printf(" Created At: %v\n Updated At: %v \n\n", issues[i].CreatedAt, issues[i].UpdatedAt)

	for j := range issues[i].Lables {
		fmt.Printf("--> %v\t", issues[i].Lables[j].Name)
		if issues[i].Lables[j].Description != "" {
			fmt.Printf("--%v\n", issues[i].Lables[j].Description)
		} else {
			fmt.Printf("\n")
		}
	}
	fmt.Printf("\n State: %v\n\n", issues[i].State)

	if len(issues[i].Assignees) == 0 {
		fmt.Printf(" This issue is not assigned to anyone. \n\n")
	} else {
		for k := range issues[i].Assignees {
			if k == 0 {
				fmt.Println(" Issue assigned to : ")
			}
			fmt.Printf(" #%v %v %v (%v)\n", k+1, issues[i].Assignees[k].Type, issues[i].Assignees[k].Login, issues[i].Assignees[k].HTMLURL)
		}
		fmt.Printf("\n\n")
	}
	fmt.Printf(" \t\t\t\t<----Description----> \n\n%v\n\n", issues[i].Body)

	fmt.Printf("No. of Commnets : %v\n", issues[i].NumberComments)

	if issues[i].NumberComments > 0 {
		fmt.Printf("\nEnter y to read comments >> ")
		answerString := "no"
		fmt.Scanf("%v", &answerString)
		if answerString == "y" || answerString == "Y" || answerString == "YES" || answerString == "yes" {
			readComments(issues[i].Number)
		}
	}

}

func readComments(id int) {
	commenturl := issueurl
	commenturl = commenturl + "/" + strconv.Itoa(id) + "/comments"

	res, err := http.Get(commenturl)
	if err != nil {
		log.Fatal(err)
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err.Error())
	}
	comment := []models.Comments{}
	json.Unmarshal(body, &comment)

	showComments(comment)
}

func showComments(comment []models.Comments) {
	fmt.Printf("\n")
	for i := range comment {
		fmt.Printf("%v %v (%v) : %v\n", comment[i].AuthorAssociation, comment[i].CommentUser.Login, comment[i].CommentUser.HTMLURL, comment[i].Body)
	}
}
